const express = require('express');
const router = express.Router();
const Message = require('../models/Message');
const User = require('../models/User');
const auth = require('../middleware/auth');

// 获取与特定用户的聊天记录
router.get('/:userId', auth, async (req, res) => {
  try {
    const messages = await Message.find({
      $or: [
        { sender: req.userId, receiver: req.params.userId },
        { sender: req.params.userId, receiver: req.userId }
      ]
    })
    .sort({ createdAt: 1 })
    .populate('sender', 'username avatar')
    .limit(50);
    
    // 将消息标记为已读
    await Message.updateMany(
      { sender: req.params.userId, receiver: req.userId, isRead: false },
      { isRead: true }
    );
    
    res.json(messages);
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    res.status(500).json({ message: '获取聊天记录失败' });
  }
});

// 发送消息
router.post('/:userId', auth, async (req, res) => {
  try {
    const { content, type, metadata } = req.body;
    const receiverId = req.params.userId;
    
    // 检查接收者是否存在
    const receiver = await User.findById(receiverId);
    if (!receiver) {
      return res.status(404).json({ message: '接收者不存在' });
    }
    
    // 检查是否是好友
    const isFriend = receiver.friends.some(
      f => f.userId.toString() === req.userId && f.status === 'accepted'
    );
    
    if (!isFriend) {
      return res.status(403).json({ message: '只能向好友发送消息' });
    }
    
    // 创建新消息
    const message = new Message({
      sender: req.userId,
      receiver: receiverId,
      content,
      type: type || 'text',
      metadata
    });
    
    await message.save();
    
    // 返回带有发送者信息的消息
    const populatedMessage = await Message.findById(message._id)
      .populate('sender', 'username avatar');
    
    res.status(201).json(populatedMessage);
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ message: '发送消息失败' });
  }
});

// 获取未读消息数量
router.get('/unread/count', auth, async (req, res) => {
  try {
    const count = await Message.countDocuments({
      receiver: req.userId,
      isRead: false
    });
    
    res.json({ count });
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
    res.status(500).json({ message: '获取未读消息数量失败' });
  }
});

module.exports = router; 